<template>
  <div class="job-view-page">
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>岗位查询</span>
        </div>
      </template>
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="岗位名称">
          <el-input v-model="queryForm.name" placeholder="请输入岗位名称" clearable style="width: 200px"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="组织">
          <el-cascader v-model="queryForm.organid" :options="organOptions" :props="cascaderProps" @change="handleOrganChange" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>岗位列表</span>
          <el-button type="primary" link @click="fetchJobList" :loading="loading">
            刷新
          </el-button>
        </div>
      </template>
      <el-button type="success" style="margin: 12px;" @click="openDialog('')">新增</el-button>
      <el-button type="danger" style="margin: 12px;" :disabled="selectedJobs.length === 0" @click="handleBatchDelete">
        批量删除 ({{ selectedJobs.length }})
      </el-button>
      <el-table v-loading="loading" :data="jobList" border stripe style="width: 100%" :height="500"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="jobnumber" label="岗位编号" width="150" align="center" />
        <el-table-column prop="jobname" label="岗位名称" width="150" align="center" />
        <el-table-column prop="organname" label="所属组织" width="180" align="center" />
        <el-table-column prop="jobnum" label="岗位人数" width="120" align="center" />
        <el-table-column prop="jobdesc" label="备注" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.pageindex" v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>

  <!-- 新增/编辑对话框 -->
  <el-dialog draggable v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form :model="jobForm" :rules="formRules" ref="jobFormRef" :label-width="120">
      <el-form-item label="岗位名称" prop="jobname">
        <el-input v-model="jobForm.jobname" placeholder="请输入岗位名称" />
      </el-form-item>
      <el-form-item label="岗位编号" prop="jobnumber">
        <el-input v-model="jobForm.jobnumber" placeholder="请输入岗位编号" />
      </el-form-item>
      <el-form-item label="所属组织" prop="organid">
        <el-cascader v-model="dialogOrganPath" :options="organOptions" :props="cascaderProps" 
          @change="handleDialogOrganChange" style="width: 100%;" clearable />
      </el-form-item>
      <el-form-item label="岗位人数" prop="jobnum">
        <el-input-number v-model="jobForm.jobnum" :min="0" :max="9999" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="jobForm.jobdesc" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import https from '@/Http/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface JobDto {
  id: number
  jobname: string
  jobnumber: string
  organid: number
  organname: string
  jobnum: number
  jobdesc: string
}

interface BindDto {
  value: number
  label: string
  children?: BindDto[]
}

interface QueryForm {
  name?: string
  organid?: number
}

interface Pagination {
  pageindex: number
  pagesize: number
  totalCount: number
  pageCount: number
}


const loading = ref(false)
const submitLoading = ref(false)
const jobList = ref<JobDto[]>([])
const organOptions = ref<BindDto[]>([])
const selectedJobs = ref<JobDto[]>([])

const selectedOrganId = ref<number | undefined>(undefined)
const dialogOrganId = ref<number | undefined>(undefined)
const dialogOrganPath = ref<number[]>([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增岗位')
const isAddMode = ref(true)
const jobFormRef = ref<FormInstance>()

// 表单数据
const jobForm = reactive({
  id: null as number | null,
  jobname: '',
  jobnumber: '',
  organid: undefined as number | undefined,
  jobnum: 0,
  jobdesc: ''
})

// 表单验证规则
const formRules: FormRules = {
  jobname: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ],
  jobnumber: [
    { required: true, message: '请输入岗位编号', trigger: 'blur' }
  ],
  organid: [
    { required: true, message: '请选择所属组织', trigger: 'change' }
  ],
  jobnum: [
    { required: true, message: '请输入岗位人数', trigger: 'blur' },
    { type: 'number', min: 0, message: '岗位人数不能小于0', trigger: 'blur' }
  ]
}

const queryForm = reactive<QueryForm>({
  name: '',
  organid: undefined
})

const pagination = reactive<Pagination>({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  pageCount: 0
})

const cascaderProps = {
  expandTrigger: 'hover' as const,
  value: 'value',
  label: 'label',
  children: 'children'
}

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T,>(payload: any): T => payload?.data ?? payload?.Data
const getPayloadMsg = (payload: any): string => payload?.msg ?? payload?.Msg ?? ''

// 获取组织下拉列表
const fetchOrganOptions = async () => {
  try {
    const res = await https.Reads({
      url: `/Organtion/Binds`,
      method: "get",
    })
    if (res.data.code == 1 || res.data.Code == 1) {
      organOptions.value = res.data.data || res.data.Data || []
    }
  } catch (error) {
    console.error('获取组织列表失败:', error)
  }
}

// 组织选择变化（查询表单）
const handleOrganChange = (value: any) => {
  if (value && value.length > 0) {
    selectedOrganId.value = value[value.length - 1]
    queryForm.organid = selectedOrganId.value
  } else {
    selectedOrganId.value = undefined
    queryForm.organid = undefined
  }
}

// 对话框组织选择变化
const handleDialogOrganChange = (value: any) => {
  if (value && value.length > 0) {
    dialogOrganId.value = value[value.length - 1]
    jobForm.organid = dialogOrganId.value
    dialogOrganPath.value = value
  } else {
    dialogOrganId.value = undefined
    jobForm.organid = undefined
    dialogOrganPath.value = []
  }
}

// 根据组织ID查找路径
const findOrganPath = (organId: number, options: BindDto[], path: number[] = []): number[] | null => {
  for (const option of options) {
    const currentPath = [...path, option.value]
    if (option.value === organId) {
      return currentPath
    }
    if (option.children && option.children.length > 0) {
      const found = findOrganPath(organId, option.children, currentPath)
      if (found) {
        return found
      }
    }
  }
  return null
}

// 表格选择变化
const handleSelectionChange = (selection: JobDto[]) => {
  selectedJobs.value = selection
}

// 获取岗位列表
const fetchJobList = async () => {
  loading.value = true
  try {
    const params: any = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize
    }

    if (queryForm.name) {
      params.name = queryForm.name
    }
    if (queryForm.organid) {
      params.organid = queryForm.organid
    }

    const { data } = await https.Reads.get(`/RBAC/ShowJob`, { params })

    if (getStatusCode(data) === 1) {
      // ApiPageing格式: { Code, Msg, TotalCount, PageCount, Data }
      jobList.value = data.Data || data.data || []
      pagination.totalCount = data.TotalCount || data.totalCount || 0
      pagination.pageCount = data.PageCount || data.pageCount || 0
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取岗位列表失败')
      jobList.value = []
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('无法获取岗位列表，请检查服务是否可用')
    jobList.value = []
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.pageindex = 1
  fetchJobList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.organid = undefined
  selectedOrganId.value = undefined
  pagination.pageindex = 1
  fetchJobList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchJobList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchJobList()
}

// 打开对话框
const openDialog = (row: JobDto | string) => {
  dialogVisible.value = true
  if (row === '') {
    // 新增模式
    dialogTitle.value = '新增岗位'
    isAddMode.value = true
    resetForm()
  } else {
    // 编辑模式
    dialogTitle.value = '编辑岗位'
    isAddMode.value = false
    const job = row as JobDto
    jobForm.id = job.id
    jobForm.jobname = job.jobname
    jobForm.jobnumber = job.jobnumber
    jobForm.organid = job.organid
    jobForm.jobnum = job.jobnum
    jobForm.jobdesc = job.jobdesc || ''
    dialogOrganId.value = job.organid
    // 查找组织路径
    const path = findOrganPath(job.organid, organOptions.value)
    dialogOrganPath.value = path || []
  }
}

// 重置表单
const resetForm = () => {
  jobForm.id = null
  jobForm.jobname = ''
  jobForm.jobnumber = ''
  jobForm.organid = undefined
  jobForm.jobnum = 0
  jobForm.jobdesc = ''
  dialogOrganId.value = undefined
  dialogOrganPath.value = []
  jobFormRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!jobFormRef.value) return

  try {
    await jobFormRef.value.validate()
    submitLoading.value = true

    if (isAddMode.value) {
      // 新增
      const { data } = await https.Writes.post("/RBAC/AddJob", {
        jobname: jobForm.jobname,
        jobnumber: jobForm.jobnumber,
        organid: jobForm.organid,
        jobnum: jobForm.jobnum,
        jobdesc: jobForm.jobdesc
      })

      if (getStatusCode(data) === 1) {
        ElMessage.success(getPayloadMsg(data) || '新增成功')
        dialogVisible.value = false
        fetchJobList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '新增失败')
      }
    } else {
      // 编辑
      const { data } = await https.Writes.put("/RBAC/UpdateJob", {
        id: jobForm.id,
        jobname: jobForm.jobname,
        jobnumber: jobForm.jobnumber,
        organid: jobForm.organid,
        jobnum: jobForm.jobnum,
        jobdesc: jobForm.jobdesc
      })

      if (getStatusCode(data) === 1) {
        ElMessage.success(getPayloadMsg(data) || '修改成功')
        dialogVisible.value = false
        fetchJobList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '修改失败')
      }
    }
  } catch (error: any) {
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败，请稍后重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 编辑
const handleEdit = (row: JobDto) => {
  openDialog(row)
}

// 删除单个岗位
const handleDelete = async (row: JobDto) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除岗位「${row.jobname}」吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )

    await deleteJobs([row.id])
  } catch {
    // 用户取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedJobs.value.length === 0) {
    ElMessage.warning('请先选择要删除的岗位')
    return
  }

  try {
    const jobNames = selectedJobs.value.map(j => j.jobname).join('、')
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedJobs.value.length} 个岗位吗？\n${jobNames}`,
      '批量删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    const ids = selectedJobs.value.map(j => j.id)
    await deleteJobs(ids)
  } catch {
    // 用户取消删除
  }
}

// 执行删除操作
const deleteJobs = async (ids: number[]) => {
  try {
    if (ids.length === 1) {
      // 单个删除
      const { data } = await https.Writes.delete("/RBAC/DelJob", {
        data: { id: ids[0] }
      })

      if (getStatusCode(data) === 1) {
        ElMessage.success(getPayloadMsg(data) || '删除成功')
        selectedJobs.value = []
        fetchJobList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '删除失败')
      }
    } else {
      // 批量删除
      const { data } = await https.Writes.delete("/RBAC/DelAllJob", {
        data: { ids: ids }
      })

      if (getStatusCode(data) === 1) {
        const count = data.data || data.Data || ids.length
        ElMessage.success(`成功删除 ${count} 个岗位`)
        selectedJobs.value = []
        fetchJobList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '删除失败')
      }
    }
  } catch (error: any) {
    console.error('删除失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '删除失败，请稍后重试')
  }
}

onMounted(() => {
  fetchOrganOptions()
  fetchJobList()
})
</script>

<style scoped>
.job-view-page {
  padding: 20px;
  background: #f5f6f8;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-form {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

